﻿//table
$.expr[':'].contains = function(a,i,m){
    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};


function ctrlInitArrowCtrlBrowser(maincontext,selector, data){
	//var context = maincontext;

	if( !maincontext.is(selector) ){
		var context = $(selector, maincontext);
	}
	
	if(context.parent().hasClass('ctrl-ajax'))
		var container = context.parent().parent();
	else
		var container = context.parent();
	
	$(function(){

		if(container.length){
			var containerHeight = container.innerHeight();
			
			if(containerHeight == 0)
				containerHeight = 500;
			var table = $(".ctrl-browser-main-table", context);
			
			 
			table.height(containerHeight  );
			
			var difSpaceForTree = 0;
			var browserCell = $(".ctrl-browser-tree-cell");
			browserCell.children().each(function(){
				if( !$(this).is(".ctrl-ajax") )
					difSpaceForTree+= $(this).outerHeight();
			});
			
			var tree = $(".ctrl-tree", context);
			tree.height( containerHeight - difSpaceForTree);
			$(".ctrl-tree-outher",context).height( (containerHeight - difSpaceForTree) - $(".ctrl-tree-toolbar",context).outerHeight() );
			
			$(".ctrl-browser-list-container",context).height(containerHeight);
			
		}else{
			
		}
	});
		
		var context = maincontext;
		

		
		var timeoutId = null;
		$(".ctrl-search", maincontext).keyup(function(){
			var val = $(this).val();
			var textBox = $(this);
			var clazz = $(".ctrl-browser-list-cell", context).find(".ctrl-ajax").eq(1).attr('class');
			if(clazz == undefined)
				var clazz = $(maincontext).parents(".ctrl-browser-list-cell").find(".ctrl-ajax").eq(1).attr('class');
			
			var selector = clazz.split(' ').slice(-1) + "";	
			
			selector = selector.replace("ctrl-ajax-","");
			var searchFn = function(){ CtrlAjax.changeStateVars(selector, {'search': 'name:LIKE:%'+textBox.val()+'%', page:0}  ); }
			if(timeoutId) clearTimeout( timeoutId );
			timeoutId = setTimeout( searchFn, 400 );
		})
		
		
		var timeoutIdTree = null;
		$(".ctrl-search-tree", context).keyup(function(){
			var val = $(this).val();
			var textBox = $(this);
			
			var searchFn = function(){
				var t = $.tree.focused();
				t.close_all();
				t.container.find('.search').removeClass('search');
				t.container.find("a").hide().parent().hide();
				t.search(val); 
				if(val==""){
					t.container.find('a').show().parent().show();
				}
			};
			if(timeoutIdTree) clearTimeout( timeoutIdTree );
			timeoutIdTree = setTimeout( searchFn, 400 );
		})
		
		$(".ctrl-action-all", context).click(function(){
			var clazz = $(".ctrl-browser-list-cell", context).find(".ctrl-ajax").eq(0).attr('class');
			var selector = clazz.split(' ').slice(-1) + ""; 
			selector = selector.replace("ctrl-ajax-","");
			CtrlAjax.changeStateVars( 
					selector, 
					{
						"selected" : -1,
						"listOnly" : 1
					} 
			);
			return false;
		});
		
		
		$(".ctrl-tree-toolbar .ctrl-action-save", context).mousedown(function(){
			$(this).attr("rel" ,"800|500|"+"products-list-ajax");
		});
		
		//console.dir(context);
		//alert("html");
		//alert(context.html());
		//alert("aaa " + $(".ctrl-tree-inner", context).length);
		//$(context).css("border", "solid 1px red");
		var tree = $(".ctrl-tree-inner", context).tree({
			ui:{
				theme_name: 'classic'
			},
			types: data.types,
			plugins : { 
				cookie: { prefix : "ctrl_jstree_" + data.id  },
				contextmenu : { 
					
					items : {
						create : {
							label	: "Dodaj folder"
						},
						edit: {
							label: "Edytuj",
							action	: function (NODE, TREE_OBJ) { 
								var folderId = $(NODE).find("a").eq(0).attr("href");
								
								if( data.editFunction ) {
									try
										{window[data.editFunction](folderId);}
									catch(e){
										alert('Bug w editFunction');
									}
								} else {	
									tmt.jquery.modalframe.open(data.editLink + "&iframe=1&id="+folderId,
										{width: 800, height: 500,
										close: function(event, ui) { 
											CtrlAjax.setStateVars( NODE,{} );
										
										}
										}
									);
								}
							},
							icon	: "rename"
							
						},
						rename : {
							label	: "Zmień nazwę", 
							icon	: "rename"
						},
						remove : {
							label	: "Usuń",
							icon	: "remove"
						}
					}
				}
			},
			
			type: {
				valid_children: 'none'
			},
			
			multitree: true,
			callback : {
				
				onsearch : function (n,t) {
					n.addClass('search');
					n.show().parents("li,a").show().find("a,li").show();
				},
				onselect : function (el) {
					
					var folderId = $(el).find("a").eq(0).attr("href");
					var type = $(el).attr("rel");
					
					if( folderId.indexOf("/") ){
						var tmp = folderId.split("/");
						folderId = tmp[tmp.length-1];
					}
					
					
					var clazz = $(".ctrl-browser-list-cell", context).find(".ctrl-ajax").eq(0).attr('class');
					var selector = clazz.split(' ').slice(-1) + ""; 
					selector = selector.replace("ctrl-ajax-","");
					
					if(folderId){
						var getKey = "ctrl-browser-selected-" + data.id;
						var get = {};
						get[getKey] = folderId;
						get["ctrl-browser-selected"] = folderId;
						get["ctrl-browser-type"] = type;
						CtrlAjax.changeStateVars( 
								selector, 
							{
								"selected" : folderId,
								"listOnly" : 1
								
							},
							get
						);
						
						if($("#search-target").length == 1 && $("#search-target").is(":visible")){
							if(searchForm)
								$("#search-target").load(searchForm.replace("_category_", folderId));
							
						}
						
						if(typeof(browserSearchFnc) != "undefined"){
							browserSearchFnc(searchForm.replace("_category_", folderId));
						}
						
					}
				},
				beforedelete: function(NODE, TREE_OBJ){
					var folderId = $(NODE).find("a").eq(0).attr("href");
					
					if($(NODE).hasClass("root")){
						alert("Nie możesz usunąć tego katalogu.");
						return false;
					}
					
					if(confirm("Czy napewno chcesz usunąć '"+TREE_OBJ.get_text(NODE)+"'?")){
						if( data.removeFunction ) {
							try
								{window[data.removeFunction](folderId);}
							catch(e){
								alert('Bug w removeFunction');
							}
						} else {	
							CtrlAjax.doAction( $(".ctrl-tree-inner", context).parents("td") ,data.treeModel,"delete",folderId, 
								{}, 
								function(response){}
							);
							return true;
						}
					}
					
				},
				onrename: function(NODE, TREE_OBJ, RB){
					var folderId = $(NODE).find("a").eq(0).attr("href");
					var name = TREE_OBJ.get_text(NODE);
					
					if( data.changeFunction ) {
						try
							{
								window[data.changeFunction](folderId, name);
								}
						catch(e){
							alert('Bug w changeFunction');
						}
					} else {
						if(folderId != ""){
							CtrlAjax.doAction( $(".ctrl-tree-inner", context).parents("td") ,data.treeModel,"save", folderId, 
									{ name:name }, 
									function(response){
										
									}
							);
							return;
						}
						
						
						var parent = TREE_OBJ.parent(NODE).find("a").eq(0).attr("href");
						var nod = NODE;
						var clazz = $(".ctrl-browser-list-cell", context).find(".ctrl-ajax").eq(0).attr('class');
						var selector = clazz.split(' ').slice(-1) + ""; 
						selector = selector.replace("ctrl-ajax-","");
						
						CtrlAjax.doAction( $(".ctrl-tree-inner", context).parents("td") ,data.treeModel,"create","", 
							{ parent_id:parent, name:name }, 
							function(response){
								$(nod).find("a").eq(0).attr("href", response.singleResponse);
								var getKey = "ctrl-browser-selected-" + data.id;
								var get = {};
								get[getKey] = response.singleResponse;
								get["ctrl-browser-selected"] = response.singleResponse;
								CtrlAjax.changeStateVars( 
										selector, 
										{
											"selected" : response.singleResponse,
											"listOnly" : 1
										},
										get
								);
							}
						);
					}
				},
				onhover: function(node){
					if($(".ui-draggable-dragging").length){
						 $(".ctrl-tree-inner a", context).removeClass("ctrl-node-drop-target");
						$(node).find("a:eq(0)").addClass("ctrl-node-drop-target");
					}
					return true;
				},
				check_move : function (NODE,REF_NODE,TYPE,TREE_OBJ,RB) {
					//if(TYPE == "inside")
					return true;
					//return false;
				},
				onmove : function (NODE,REF_NODE,TYPE,TREE_OBJ,RB) {
					var nodeId = $("a",NODE).attr("href");
					var targetId = 1;
					if(TYPE == "inside"){
						targetId = $("a",REF_NODE).attr("href");
						if(targetId != undefined){
							CtrlAjax.doAction( $(".ctrl-tree-inner", context).parents("td") ,data.treeModel,"save", nodeId, 
								{ parent_id:targetId }, 
								function(response){
									if(response.singleResponse == undefined) {
										CtrlAjax.reload($(".ctrl-tree-inner", context).parents("td"));
									}
									$("a",NODE).click();
								}
							);
						}
					}else{
						targetId = $(REF_NODE).parents("li:eq(0)").find("a:eq(0)").attr("href");
						var moveRelId =  $(REF_NODE).find("a:eq(0)").attr("href");
						if(targetId != undefined && moveRelId != undefined){
							CtrlAjax.doAction( $(".ctrl-tree-inner", context).parents("td") ,data.treeModel,"move", nodeId, 
								{ parent_id:targetId }, 
								function(response){
									if(response.singleResponse == undefined) {
										CtrlAjax.reload($(".ctrl-tree-inner", context).parents("td"));
									}
									$("a",NODE).click();
								},
								{refId: moveRelId, parent_id:targetId, insertType: TYPE }
							);
						}
						
						
						return false;
					}
					if(targetId != undefined){
						return false;
					}
				}
			}
		});
		
		//$(".ctrl-tree-inner a", context).tooltip({showURL: false});
		
		if( !$.tree.reference( tree ).selected )
			$.tree.reference( tree ).select_branch("#ctrl-ctrlbrowser-tree-1");
	//});
	


	
		
	
}